#include "ReceverDialog.h"
#include "ui_ReceverDialog.h"

ReceverDialog::ReceverDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::ReceverDialog)
{
    ui->setupUi(this);
    udpsocket = new QUdpSocket(this);
    isStarted = false;
}

ReceverDialog::~ReceverDialog()
{
    delete ui;
}

//点击开始接收按钮的槽函数
void ReceverDialog::on_pushButton_clicked()
{
    if (isStarted == false) {
        isStarted = true;
        //获取接受消息的端口并绑定
        port = ui->lineEdit->text().toShort();
        udpsocket->bind(port);

        ui->lineEdit->setEnabled(false);
        ui->pushButton->setText("停止接收");
        //当套接字有数据到来时, 连接信号与接受消息槽函数
        connect (udpsocket, SIGNAL(readyRead()),
                 this, SLOT(messageRecevied()));
    } else {
        isStarted = false;
        udpsocket->close ();
        ui->lineEdit->setEnabled(true);
        ui->pushButton->setText("开始接收");
    }
}

//接受广播消息的槽函数
void ReceverDialog::messageRecevied ()
{
    if (udpsocket->hasPendingDatagrams()) {
        //准备保存套接字数据的缓冲区
        QByteArray buf;
        buf.resize(udpsocket->pendingDatagramSize());
        //读数据包
        udpsocket->readDatagram(buf.data(),buf.size());
        //在ui显示数据
        ui->listWidget->addItem(buf);
        //回滚到消息底部
        ui->listWidget->scrollToBottom();
    }
}






